﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ShowProcess3 : MonoBehaviour {
	public GameObject cubePrefab;
	public List<GameObject> cubeList = new List<GameObject>();

	public InputField xInputField;
	public InputField yInputField;
	public InputField eInputField;
	public InputField lambdaInputField;

	public Text xText;
	public Text yText;
	public Text zText;
	public GameObject answerGo;

	float x;
	float y;
	float e;
	float lambda;

	float fx;
	float fy;
	float x1;
	float y1;

	void Start() {
		GetInputFieldParam();
		AddCube(x, y);
		fx = Fx(x, y);
		fy = Fy(x, y);
		UpdateText();
	}

	public void TenSteps() {
		for (int i = 0; i < 10; i++) {
			OneStep();
		}
	}

	public void OneStep() {
		GetInputFieldParam();
		Calculate();
		AddCube(x, y);
		UpdateText();
		SetInputFieldParam();
	}

	void SetInputFieldParam() {
		xInputField.text = x.ToString();
		yInputField.text = y.ToString();
		eInputField.text = e.ToString();
		lambdaInputField.text = lambda.ToString();
	}

	void GetInputFieldParam() {
		x = float.Parse(xInputField.text);
		y = float.Parse(yInputField.text);
		e = float.Parse(eInputField.text);
		lambda = float.Parse(lambdaInputField.text);
	}

	void UpdateText() {
		xText.text = "x: " + x.ToString();
		yText.text = "y: " + y.ToString();
		zText.text = "z: " + F(x, y).ToString();
	}

	void Calculate() {
		x += lambda * fx;
		y += lambda * fy;
		fx = Fx(x, y);
		fy = Fy(x, y);
		if (Mathf.Sqrt(fx * fx + fy * fy) <= e) {
			answerGo.SetActive(true);//输出结果
		}
		else {
			answerGo.SetActive(false);
		}
	}

	float F(float x, float y) {
		return DrawFunction3.Instance.zAmplificationRatio / (x * x + y * y + 2);
	}
	float Fx(float x, float y) {
		return -2 * x / ((x * x + y * y + 2) * (x * x + y * y + 2));
	}
	float Fy(float x, float y) {
		return -2 * y / ((x * x + y * y + 2) * (x * x + y * y + 2));
	}

	void AddCube(float x, float y, float z) {
		GameObject go = Instantiate(cubePrefab, new Vector3(x, y, z), Quaternion.identity);
		go.GetComponent<MeshRenderer>().material.color = Color.red;
		cubeList.Add(go);
	}
	void AddCube(float x, float y) {
		AddCube(this.x, F(this.x, this.y), this.y);
	}

}
